package kyj_service

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/goravel/framework/facades"
	"io"
	"net/http"
	"time"
)

type KyjService struct {
}

func NewKyjService() *KyjService {
	return &KyjService{}
}

const (
	URL          = "https://kyj-api.com"
	KEYIJIETOKEN = "keyijie_token"
)

const (
	APIURL = "/oauth/token"
)

type AuthReq struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type"`
	ExpiresIn   int    `json:"expires_in"`
}

func (s *KyjService) Auth() (error, string) {
	if !facades.Cache().Has(KEYIJIETOKEN) {
		url := fmt.Sprintf("%s/%s/oauth/token?grant_type=client_credentials", URL, APIURL)
		token := facades.Config().Get("keyijie.BasicAuth")
		//定义client客户端
		client := &http.Client{}
		//定义请求
		req, _ := http.NewRequest("POST", url, nil)
		//设置请求头
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("Authorization", fmt.Sprintf("Basic %s", token))
		//发送请求
		resp, _ := client.Do(req)
		authByte := []byte{}
		authReq := AuthReq{}
		//解析返回结果
		if resp.StatusCode == 200 {
			authByte, _ = io.ReadAll(resp.Body)
			json.Unmarshal(authByte, &authReq)
			//ExpiresIn单位为秒
			duaration := time.Duration(authReq.ExpiresIn) * time.Second
			err := facades.Cache().Put(KEYIJIETOKEN, authReq.AccessToken, duaration)
			if err != nil {
				return err, ""
			}
			return nil, authReq.AccessToken
		}
		defer resp.Body.Close()
		return errors.New("鉴权错误"), ""
	} else {
		return nil, facades.Cache().GetString(KEYIJIETOKEN)
	}
}
